﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Infrastructure.Model.DI;
using Microsoft.Extensions.Logging;
using Model.EntityModel.Auth;
using Model.EntityModel.SysModel;
using Repository.IRepository.ISysRepository;

namespace Repository.Repository.SysRepository
{
    /// <summary>
    /// 用户-组关联表仓储层实现
    /// </summary>
    [AppService(ServiceType = typeof(IUserGroupRepository), ServiceLifetime = LifeTime.Transient)]
    public class UserGroupRepository : SqlSugarBaseRepository<UserGroup>, IUserGroupRepository
    {
        private readonly ILogger<UserGroupRepository> _logger;

        public UserGroupRepository(ILogger<UserGroupRepository> logger)
        {
            _logger = logger;
        }

        /// <summary>
        /// 获取用户关联的所有组别
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns>用户组关联列表</returns>
        public List<UserGroup> GetUserGroups(string userId)
        {
            try
            {
                return _db.Queryable<UserGroup>()
                    .Where(ug => ug.UserId == userId)
                    .ToList();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"获取用户组别关联失败，用户ID: {userId}");
                throw new Exception("获取用户组别关联时发生错误", ex);
            }
        }

        public bool AddUsersToGroupBulk(List<string> userIds, string groupId)
        {
            if (!userIds.Any()) return false;

            var newAssociations = userIds.Select(userId => new UserGroup
            {
                Id = Guid.NewGuid().ToString(),
                UserId = userId,
                GroupId = groupId,
                IsActive = "Y",
                CreatedAt = DateTime.Now
            }).ToList();

            return _db.Insertable(newAssociations).ExecuteCommand() > 0;
        }

        public bool RemoveUsersFromGroupBulk(List<string> userIds, string groupId)
        {
            if (!userIds.Any()) return false;

            return _db.Deleteable<UserGroup>()
                .Where(ug => userIds.Contains(ug.UserId) && ug.GroupId == groupId)
                .ExecuteCommand() > 0;
        }
        /// <summary>
        /// 添加组别到用户
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="groupIds">组别ID列表</param>
        /// <returns>操作结果</returns>
        public bool AddGroupsToUser(string userId, List<string> groupIds)
        {
            try
            {
                if (groupIds == null || !groupIds.Any())
                {
                    _logger.LogWarning("添加组别到用户时，组别ID列表为空");
                    return false;
                }

                // 获取用户已关联的组别
                var existingGroups = _db.Queryable<UserGroup>()
                    .Where(ug => ug.UserId == userId)
                    .Select(ug => ug.GroupId)
                    .ToList();

                // 筛选出新的关联
                var newGroups = groupIds.Except(existingGroups)
                    .Select(groupId => new UserGroup
                    {
                        Id = Guid.NewGuid().ToString(),
                        UserId = userId,
                        GroupId = groupId,
                        IsActive = "Y",
                        CreatedAt = DateTime.Now
                    }).ToList();

                if (newGroups.Any())
                {
                    return _db.Insertable(newGroups).ExecuteCommand() > 0;
                }
                return true;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"添加组别到用户失败，用户ID: {userId}");
                throw new Exception("添加组别到用户时发生错误", ex);
            }
        }

        /// <summary>
        /// 从用户移除组别
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="groupIds">组别ID列表</param>
        /// <returns>操作结果</returns>
        public bool RemoveGroupsFromUser(string userId, List<string> groupIds)
        {
            try
            {
                if (groupIds == null || !groupIds.Any())
                {
                    _logger.LogWarning("从用户移除组别时，组别ID列表为空");
                    return false;
                }

                return _db.Deleteable<UserGroup>()
                    .Where(ug => ug.UserId == userId && groupIds.Contains(ug.GroupId))
                    .ExecuteCommand() > 0;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"从用户移除组别失败，用户ID: {userId}");
                throw new Exception("从用户移除组别时发生错误", ex);
            }
        }

        /// <summary>
        /// 更新用户-组别关联状态
        /// </summary>
        /// <param name="relationId">关联ID</param>
        /// <param name="isActive">激活状态(Y/N)</param>
        /// <returns>操作结果</returns>
        public bool UpdateUserGroupStatus(string relationId, string isActive)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(relationId))
                {
                    _logger.LogWarning("更新关联状态时，关联ID为空");
                    return false;
                }

                if (isActive != "Y" && isActive != "N")
                {
                    _logger.LogWarning($"更新关联状态时，无效的状态值: {isActive}");
                    throw new ArgumentException("状态值必须是Y或N", nameof(isActive));
                }

                return _db.Updateable<UserGroup>()
                    .SetColumns(ug => new UserGroup
                    {
                        IsActive = isActive,
                        CreatedAt = DateTime.Now
                    })
                    .Where(ug => ug.Id == relationId)
                    .ExecuteCommand() > 0;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"更新用户组别关联状态失败，关联ID: {relationId}");
                throw new Exception("更新用户组别关联状态时发生错误", ex);
            }
        }

        /// <summary>
        /// 获取用户所属的有效组别
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns>组别列表</returns>
        public List<Group> GetActiveGroupsForUser(string userId)
        {
            try
            {
                return _db.Queryable<UserGroup>()
                    .LeftJoin<Group>((ug, g) => ug.GroupId == g.Id)
                    .Where((ug, g) => ug.UserId == userId && ug.IsActive == "Y" && g.IsActive == "Y")
                    .Select((ug, g) => g)
                    .ToList();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"获取用户有效组别失败，用户ID: {userId}");
                throw new Exception("获取用户有效组别时发生错误", ex);
            }
        }

        /// <summary>
        /// 检查用户-组关联是否存在
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="groupId">组别ID</param>
        /// <returns>是否存在关联</returns>
        public bool UserGroupExists(string userId, string groupId)
        {
            try
            {
                return _db.Queryable<UserGroup>()
                    .Where(ug => ug.UserId == userId && ug.GroupId == groupId)
                    .Count() > 0;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"检查用户组别关联存在性失败，用户ID: {userId}, 组别ID: {groupId}");
                throw new Exception("检查用户组别关联存在性时发生错误", ex);
            }
        }
    }
}
